'''web框架的职责转么处理动态资源请求'''
import pymysql
import json

# 获取首页数据
import time
route_list = [
    # Django用的框架是list，flask是用的装饰器
    # ("/index.html", index),
    # ("/center.html", center),
]

# 定义一个带有参数的装饰器
def route(path):
    def decorator(func):
        # 当装饰器执行的时候就需要把路由添加到列表里面
        # 当装饰的时候只添加一次路由
        route_list.append((path,func))
        def inner():
            result = func()
            return result
        return  inner
    return decorator

@route("/index.html")
def index():
    status = "200 OK"
    headers = [("Server", "PWS/1.1")]
    # 获取当前时间
    # response_body = time.ctime()
    # 1.打开模板
    # 2.替换数据库里面查询的数据
    conn=pymysql.connect(user='pantest',
                    password='pantest_2021',
                    host='192.168.0.137',
                    database='stock_db',
                    port=3306,
                    charset='utf8'
                    )
    cursor=conn.cursor()
    sql='select * from info;'
    cursor.execute(sql)
    # 获取查询结果
    # 遍历每一条数据
    result=cursor.fetchall()
    cursor.close()
    conn.close()
    data=''
    for row in result:
        data += '''<tr>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
        <td>%s</td>
        <td><input type="button" value="添加"></td>
        </tr>
        '''% row

    with open('./template/index.html', 'r', encoding="utf-8") as file:
        filedata = file.read()
        # 模拟数据库内容
        response_body = filedata.replace("{%content%}", data)
    return status, headers, response_body

@route("/center.html")
def center():
    status = "200 OK"
    headers = [("Server", "PWS/1.1")]
    # 获取当前时间
    # response_body = time.ctime()
    # 1.打开模板
    # 2.替换数据库里面查询的数据
    with open('./template/center.html', 'r', encoding="utf-8") as file:
        filedata = file.read()
        # 模拟数据库内容
        response_body = filedata.replace("{%content%}", "")
    return status, headers, response_body

@route("/center_data.html")
# 个人中心数据接口
def center_data():
    # 把数据库数据查询出来，然后把查询数据转成json
    conn = pymysql.connect(user='pantest',
                           password='pantest_2021',
                           host='192.168.0.137',
                           database='stock_db',
                           port=3306,
                           charset='utf8'
                           )
    cursor = conn.cursor()
    sql = 'SELECT i.code,i.short,i.chg,i.turnover,i.price,i.highs,f.note_info from info as i INNER JOIN focus as f on i.id = f.info_id;'
    cursor.execute(sql)
    # 获取查询结果
    # 遍历每一条数据
    result = cursor.fetchall()
    # 把元组转成列表字典
    center_data_list=[{"code":row[0],
      "short": row[1],
      "chg": row[2],
      "turnover": row[3],
      "price": str(row[4]),
      "highs": str(row[5]),
      "note_info": row[6],
      } for row in result]
    # 把列表转成json
    # 在控制台显示中文
    json_str=json.dumps(center_data_list,ensure_ascii=False)
    cursor.close()
    conn.close()
    status = "200 OK"
    headers = [("Server", "PWS/1.1"),
               # 指定编码格式，因为没有模板文件，可以通过响应头指定编码格式
               ("Content-Type", "text/html;charset=utf-8")]
    return status, headers, json_str

# 处理404
def not_found():
    status = "404 Not Found"
    headers = [("Server", "PWS/1.1")]
    # 获取当前时间
    response_body = "not found"
    return status, headers, response_body


# 路由列表
# route_list = [
#     ("/index.html", index),
#     ("/center.html", center),
# ]


# 处理动态资源请求

def handle_request(env):
    # 获取动态请求的资源路径
    request_path = env["request_path"]
    for path, func in route_list:
        if request_path == path:
            result = func()
            return result
    else:
        result = not_found()
        return result
    # 判断请求的动态资源路径，选择指定的函数处理对应的动态资源请求
    # if request_path=='/index.html':
    #     result = index()
    #     return result
    # else:
    #     # 没有动态资源数据，返回404
    #     result = not_found()
    #     return  result
if __name__ == '__main__':
    center_data()
